//
//  BBScanQRCodeController.swift
//  BusinessBao
//
//  Created by Chen on 2017/7/21.
//  Copyright © 2017年 Chen. All rights reserved.
//

import UIKit
import AVFoundation

class BBScanQRCodeController: BBBaseViewController, AVCaptureMetadataOutputObjectsDelegate {
    
    lazy var session: AVCaptureSession = {
        return AVCaptureSession()
    }()
    lazy var inputDevice: AVCaptureDeviceInput? = {
        let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
        do {
            return try AVCaptureDeviceInput(device: device)
        } catch {
            return nil
        }
    }()
    lazy var dataOutput: AVCaptureMetadataOutput = {
        return AVCaptureMetadataOutput()
    }()
    /// 预览图层
    lazy var previewLayer: AVCaptureVideoPreviewLayer = {
        return AVCaptureVideoPreviewLayer(session: self.session)
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title = "扫描二维码"

        self.setupSesstion()
        self.setupLayers()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        /// 开始扫描
        self.session.startRunning()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        self.session.stopRunning()
    }
    
    /// 设置图层
    func setupLayers() {
        previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
        previewLayer.frame = view.bounds
        view.layer.insertSublayer(previewLayer, at: 0)
    }
    
    private func setupSesstion() {
        // 1. 判断是否能够添加设备
        if !session.canAddInput(inputDevice) {
            print("无法添加输入设备")
            return
        }
        
        // 2. 判断能否添加输出数据
        if !session.canAddOutput(dataOutput) {
            print("无法添加输出数据")
            return
        }
        
        // 3. 添加设备
        session.addInput(inputDevice)
        session.addOutput(dataOutput)
        
        // 4. 设置扫描数据类型
        dataOutput.metadataObjectTypes = [
            AVMetadataObjectTypeEAN13Code,
            AVMetadataObjectTypeEAN8Code,
            AVMetadataObjectTypeCode128Code,
            AVMetadataObjectTypeQRCode
        ]
        // 5. 设置输出代理
        dataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
    }
    
    // MARK: - AVCaptureMetadataOutputObjectsDelegate
    func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {
        for object in metadataObjects {
            print(object)
        }
    }
 
}
